package com.qinggeng.project.system.service.impl;

import java.util.List;

import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.project.api.dto.CartDto;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.domain.OrdersGoods;
import com.qinggeng.project.system.mapper.GoodsMapper;
import com.qinggeng.project.system.mapper.OrdersGoodsMapper;
import com.qinggeng.project.system.mapper.OrdersMapper;
import com.qinggeng.project.system.service.IGoodsService;
import com.qinggeng.project.system.service.IOrdersGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qinggeng.project.system.mapper.UserGoodsLimitRecordMapper;
import com.qinggeng.project.system.domain.UserGoodsLimitRecord;
import com.qinggeng.project.system.service.IUserGoodsLimitRecordService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.swing.undo.CannotUndoException;

/**
 * 用户商品限购记录Service业务层处理
 *
 * @author smallfish
 * @date 2020-12-05
 */
@Slf4j
@Service
public class UserGoodsLimitRecordServiceImpl implements IUserGoodsLimitRecordService
{
    @Resource
    private UserGoodsLimitRecordMapper userGoodsLimitRecordMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private OrdersGoodsMapper ordersGoodsMapper;



    /**
     * 查询用户商品限购记录
     *
     * @param recordId 用户商品限购记录ID
     * @return 用户商品限购记录
     */
    @Override
    public UserGoodsLimitRecord getUserGoodsLimitRecordById(Long recordId)
    {
        return userGoodsLimitRecordMapper.getUserGoodsLimitRecordById(recordId);
    }

    @Override
    public UserGoodsLimitRecord getUserGoodsLimitRecordByUserIdAndGoodsId(Long userId,Long goodsId){
        return userGoodsLimitRecordMapper.getUserGoodsLimitRecordByUserIdAndGoodsId(userId,goodsId);
    }

    /**
     * 查询用户商品限购记录列表
     *
     * @param userGoodsLimitRecord 用户商品限购记录
     * @return 用户商品限购记录
     */
    @Override
    public List<UserGoodsLimitRecord> listUserGoodsLimitRecord(UserGoodsLimitRecord userGoodsLimitRecord)
    {
        return userGoodsLimitRecordMapper.listUserGoodsLimitRecord(userGoodsLimitRecord);
    }

    /**
     * 新增用户商品限购记录
     *
     * @param userGoodsLimitRecord 用户商品限购记录
     * @return 结果
     */
    @Override
    public int insertUserGoodsLimitRecord(UserGoodsLimitRecord userGoodsLimitRecord)
    {
        return userGoodsLimitRecordMapper.insertUserGoodsLimitRecord(userGoodsLimitRecord);
    }

    /**
     * 修改用户商品限购记录
     *
     * @param userGoodsLimitRecord 用户商品限购记录
     * @return 结果
     */
    @Override
    public int updateUserGoodsLimitRecord(UserGoodsLimitRecord userGoodsLimitRecord)
    {
        return userGoodsLimitRecordMapper.updateUserGoodsLimitRecord(userGoodsLimitRecord);
    }

    @Override
    public boolean updateUserGoodsGoodsLimitRecordBuyNum(Long recordId, int buyNum) {
        return userGoodsLimitRecordMapper.updateUserGoodsGoodsLimitRecordBuyNum(recordId,buyNum)>0;
    }

    /**
     * 批量删除用户商品限购记录
     *
     * @param recordIds 需要删除的用户商品限购记录ID
     * @return 结果
     */
    @Override
    public int deleteUserGoodsLimitRecordByIds(Long[] recordIds)
    {
        return userGoodsLimitRecordMapper.deleteUserGoodsLimitRecordByIds(recordIds);
    }

    /**
     * 删除用户商品限购记录信息
     *
     * @param recordId 用户商品限购记录ID
     * @return 结果
     */
    @Override
    public int deleteUserGoodsLimitRecordById(Long recordId)
    {
        return userGoodsLimitRecordMapper.deleteUserGoodsLimitRecordById(recordId);
    }

    @Override
    public int insertUserGoodsLimitRecord(Orders orders) {
        if(null==orders) {
            throw new CustomException("订单不存在", ShowTypeEnum.用户.getValue());
        }
        List<OrdersGoods> ordersGoodsList = ordersGoodsMapper.selectOrderGoodListByOrdersId(orders.getOrdersId());
        if (CollectionUtils.isEmpty(ordersGoodsList)) {
            throw new CustomException("订单商品列表为空");
        }
        int rows = 0;
        for (OrdersGoods ordersGoods : ordersGoodsList
        ) {
            //根据商品Id获取商品限购数量
            Integer limitNum = goodsMapper.getGoodsLimitNum(ordersGoods.getGoodsId());
            //如果不限购，不添加记录
            if (null == limitNum) {
                continue;
            }
            //查询用户限购商品购买记录
            UserGoodsLimitRecord record = userGoodsLimitRecordMapper.getUserGoodsLimitRecordByUserIdAndGoodsId(orders.getUserId(), ordersGoods.getGoodsId());
            //存在记录，更新用户购买数量
            if (record != null) {
                int result = userGoodsLimitRecordMapper.updateUserGoodsGoodsLimitRecordBuyNum(record.getRecordId(), ordersGoods.getGoodsNum());
                if (result > 0) {
                    rows++;
                }
                continue;
            }
            //记录不存在，新建用户商品限购记录
            record = new UserGoodsLimitRecord();
            record.setGoodsId(ordersGoods.getGoodsId());
            record.setUserId(orders.getUserId());
            record.setLimitNum(limitNum);
            record.setBuyNum(ordersGoods.getGoodsNum());
            record.setBuyDate(DateUtils.getNowDate());
            int result = userGoodsLimitRecordMapper.insertUserGoodsLimitRecord(record);
            if (result > 0) {
                rows++;
            }
        }
        return rows;
    }


        @Override
    public Integer getUserGoodsLimitRemainNum(Long goodsId) {
        //根据id查询商品限购数量
        Integer limitNum=goodsMapper.getGoodsLimitNum(goodsId);
        //如果商品不限购
        if(null==limitNum){
            return null;
        }
        if(!ApiUtils.getIsLogin()){
            return limitNum;
        }
        //查询用户限购商品购买记录
        UserGoodsLimitRecord record = userGoodsLimitRecordMapper.getUserGoodsLimitRecordByUserIdAndGoodsId(ApiUtils.getUserId(), goodsId);
        //用户今日已购数量
        int buyNum=record!=null&&record.getBuyNum()!=null?record.getBuyNum():0;

        return limitNum-buyNum;
    }

    @Override
    public boolean checkIsGoodsLimit(Long goodsId,Integer goodsNum,Integer cartNum){

        Goods goods=goodsMapper.selectGoodsById(goodsId);
        if(null==goods){
            log.error("ID："+goodsId+"的商品不存在");
            throw new CustomException("商品不存在");
        }
        if(null==goods.getLimitNum()){
            return true;
        }
        //查询用户限购商品购买记录
        Integer remainNum=this.getUserGoodsLimitRemainNum(goodsId);
        if(null==remainNum){
            return true;
        }
        if(remainNum<1){
            throw new CustomException(goods.getGoodsName()+"每日限购"+goods.getLimitNum()+"份，您已达限购份额！",ShowTypeEnum.用户.getValue());
        }
        if(remainNum<cartNum){
            throw new CustomException(goods.getGoodsName()+"每日限购"+goods.getLimitNum()+"份，您还可购"+remainNum+"份！",ShowTypeEnum.用户.getValue());
        }
        if(remainNum<cartNum+goodsNum){
            if((remainNum=remainNum-cartNum)<1){
                throw new CustomException(goods.getGoodsName()+"每日限购"+goods.getLimitNum()+"份，您已达限购份额！",ShowTypeEnum.用户.getValue());
            }
            throw new CustomException(goods.getGoodsName()+"每日限购"+goods.getLimitNum()+"份，您还可购"+remainNum+"份！",ShowTypeEnum.用户.getValue());
        }
        return true;


    }

    @Override
    public boolean checkIsGoodsLimitList(List<CartDto> cartDtos,List<String> loseGoodsNameList) {
        //查询用户限购商品购买记录
        List<UserGoodsLimitRecord> userGoodsLimitRecordList = userGoodsLimitRecordMapper.getUserGoodsLimitRecordByUserId(ApiUtils.getUserId());
        for (CartDto cartDto : cartDtos) {
            if (cartDto.getIslose()) {
                loseGoodsNameList.add(cartDto.getGoodsName());
                continue;
            }

            if (cartDto.getKeepNum() <= 0 || cartDto.getKeepNum() < cartDto.getGoodsNum()) {
                continue;
            }
            if (CollectionUtils.isEmpty(userGoodsLimitRecordList)){
                Integer limitNum = cartDto.getLimitNum();
                Integer buyNum = cartDto.getGoodsNum();
                if (limitNum == null || limitNum == 0){
                    continue;
                }
                if(limitNum >= buyNum){
                    continue;
                }
                throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，无法继续购买！",ShowTypeEnum.用户.getValue());
            }else {
                for (UserGoodsLimitRecord userGoodsLimitRecord : userGoodsLimitRecordList) {
                    if (cartDto.getGoodsId().equals(userGoodsLimitRecord.getGoodsId())){
                        //根据id查询商品限购数量
                        Integer limitNum=cartDto.getLimitNum();
                        if (null==limitNum || limitNum == 0){
                            continue;
                        }

                        //用户今日已购数量
                        Integer buyNum=userGoodsLimitRecord.getBuyNum()!=null?userGoodsLimitRecord.getBuyNum():0;
                        Integer remainNum = limitNum - buyNum;
                        if(remainNum==0){
                            throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，您已达限购份额！",ShowTypeEnum.用户.getValue());
                        }
                        if(cartDto.getGoodsNum()<=remainNum){
                            continue;
                        }

                        throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，您已购"+buyNum+"份！",ShowTypeEnum.用户.getValue());
                    }
                }
            }

        }
        return true;
    }

    @Override
    public boolean checkIsGoodsLimitList(List<CartDto> cartDtos) {
        //查询用户限购商品购买记录
        List<UserGoodsLimitRecord> userGoodsLimitRecordList = userGoodsLimitRecordMapper.getUserGoodsLimitRecordByUserId(ApiUtils.getUserId());
        for (CartDto cartDto : cartDtos) {
            if (CollectionUtils.isEmpty(userGoodsLimitRecordList)){
                Integer limitNum = cartDto.getLimitNum();
                Integer buyNum = cartDto.getGoodsNum();
                if (limitNum == null || limitNum == 0){
                    continue;
                }
                if(limitNum >= buyNum){
                    continue;
                }
                throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，无法继续购买！",ShowTypeEnum.用户.getValue());
            }else {
                for (UserGoodsLimitRecord userGoodsLimitRecord : userGoodsLimitRecordList) {
                    if (cartDto.getGoodsId().equals(userGoodsLimitRecord.getGoodsId())){
                        //根据id查询商品限购数量
                        Integer limitNum=cartDto.getLimitNum();
                        if (null==limitNum || limitNum == 0){
                            continue;
                        }

                        //用户今日已购数量
                        Integer buyNum=userGoodsLimitRecord.getBuyNum()!=null?userGoodsLimitRecord.getBuyNum():0;
                        Integer remainNum = limitNum - buyNum;
                        if(remainNum==0){
                            throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，您已达限购份额！",ShowTypeEnum.用户.getValue());
                        }
                        if(cartDto.getGoodsNum()<=remainNum){
                            continue;
                        }

                        throw new CustomException(cartDto.getGoodsName()+"每日限购"+limitNum+"份，您已购"+buyNum+"份！",ShowTypeEnum.用户.getValue());
                    }
                }
            }

        }
        return true;
    }
}
